package com.dengcj.entity;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.util.List;
import java.util.Map;

/**
 * @author dengchunjie
 * @Description: 通用API结果对象
 * @date 2022/1/12 15:44
 */
public class ApiResult<T> {

    private boolean status = true;
    private String msg = "success";
    private T data = null;

    public String success(T data){
        this.status = true;
        this.msg = "success";
        this.data = data;

        return toString();
    }

    public String success(){
        this.status = true;
        this.msg = "success";

        return toString();
    }

    public String error(String msg){
        this.status = false;
        this.msg = msg;
        this.data = null;

        return toString();
    }

    @Override
    public String toString(){
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("status", status);
        jsonObject.set("msg", msg);

        if(data instanceof String){
            jsonObject.set("data", data);
        } else if(data instanceof Map){
            jsonObject.set("data", JSONUtil.parseObj(data));
        } else if(data instanceof List){
            jsonObject.set("data", JSONUtil.parseArray(data));
        }

        return jsonObject.toString();
    }
}
